# Start Node.js Server Production Environment

# 保存原始工作目录
$originalDir = Get-Location

# Check and start required dependencies (MySQL and Redis)
function Check-And-Start-Dependencies {
    Write-Host "=========================================" -ForegroundColor Cyan
    Write-Host "Checking required dependencies..." -ForegroundColor Cyan
    Write-Host "=========================================" -ForegroundColor Cyan
    
    # Check and start MySQL if not running
    $mysqlRunning = docker ps | Select-String -Pattern "mysql-server"
    if (-not $mysqlRunning) {
        Write-Host "MySQL service not running. Starting MySQL..." -ForegroundColor Yellow
        try {
            . "$PSScriptRoot\01start_mysql.ps1"
            Write-Host "MySQL started successfully." -ForegroundColor Green
        } catch {
            Write-Host "Failed to start MySQL: $_" -ForegroundColor Red
            exit 1
        }
    } else {
        Write-Host "MySQL service is already running." -ForegroundColor Green
    }
    
    # Check and start Redis if not running
    $redisRunning = docker ps | Select-String -Pattern "redis-server"
    if (-not $redisRunning) {
        Write-Host "Redis service not running. Starting Redis..." -ForegroundColor Yellow
        try {
            . "$PSScriptRoot\02start_redis.ps1"
            Write-Host "Redis started successfully." -ForegroundColor Green
        } catch {
            Write-Host "Failed to start Redis: $_" -ForegroundColor Red
            exit 1
        }
    } else {
        Write-Host "Redis service is already running." -ForegroundColor Green
    }
    
    Write-Host "=========================================" -ForegroundColor Cyan
    Write-Host "All dependencies checked." -ForegroundColor Cyan
    Write-Host "=========================================" -ForegroundColor Cyan
}

# Check and start dependencies
Check-And-Start-Dependencies

Write-Host "Starting Node.js Server Production Environment..."

# Change to Docker configuration directory
Set-Location -Path "$PSScriptRoot\server"

# Stop and remove only the node-server container if it exists
Write-Host "Stopping node-server container if it exists..." -ForegroundColor Yellow
docker stop node-server 2>$null
Write-Host "Removing node-server container if it exists..." -ForegroundColor Yellow
docker rm node-server 2>$null

# Build and start containers
docker-compose -f 3-docker-compose-node-server-prod.yml up -d --build

echo "Node.js Server Production Environment started successfully!"

# 恢复原始工作目录
Set-Location -Path $originalDir